package com.luoye.lj.platform.controller;

import com.luoye.lj.platform.controller.data.SimpleMUserDetailResult;
import com.luoye.lj.platform.controller.log.ManagerDelUserGenerator;
import com.luoye.lj.platform.controller.log.ManagerSaveGenerator;
import com.luoye.lj.platform.controller.log.ManagerSaveUserGenerator;
import com.luoye.lj.platform.dao.IManageMenuDao;
import com.luoye.lj.platform.model.UserModel;
import com.luoye.lj.platform.model.domain.RoleInfo;
import com.luoye.lj.platform.model.domain.SearchParams;
import com.luoye.lj.platform.model.domain.muser.*;
import com.luoye.lj.platform.model.enums.UserStatus;
import com.luoye.lj.platform.pojo.dbo.ManageMenuDbo;
import com.luoye.lj.platform.pojo.dbo.ManageMenuDboCollection;
import com.luoye.lj.platform.pojo.dbo.ManageMenuDboSearchCondition;
import com.luoye.lj.platform.pojo.vo.ManageMenuVo;
import com.luoye.lj.platform.service.IManageMenuService;
import com.luoye.lj.platform.service.IMuserservice;
import com.luoye.lj.util.converter.DataConverter;
import com.luoye.lj.util.converter.PojoConvertUtil;
import com.luoye.lj.util.mvc.annotation.OperateLog;
import com.luoye.lj.util.mvc.data.SimpleListResult;
import com.luoye.lj.util.mvc.data.SimpleResponseBody;
import com.luoye.lj.util.mvc.util.PageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Dave Liu
 * Date: 15-11-4
 * Time: 下午2:44
 * To change this template use File | Settings | File Templates.
 */

@Controller
@RequestMapping("/system/manager")
public class ManagerController {
    protected static final Logger logger = LoggerFactory.getLogger(ManagerController.class.getSimpleName());
    @Resource
    UserDetailsService customUserDetailsService;
    @Resource
    PasswordEncoder passwordEncoder;
    @Autowired
    private IMuserservice muserservice;
    @Autowired
    private IManageMenuService manageMenuService;

    public static boolean isDeveloper() {
        if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof UserModel) {
            UserModel userDetails = (UserModel) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            MUserDetail mUserDetail = userDetails.getmUserDetail();
            List<RoleInfo> roleInfoList = mUserDetail.getRoleInfoList();
            if (!CollectionUtils.isEmpty(roleInfoList)) {
                for (RoleInfo roleInfo : roleInfoList) {
                    if ("R_Developer".equals(roleInfo.getRolename())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private boolean isDeveloper(List<RoleInfo> roleInfoList) {
        if (!CollectionUtils.isEmpty(roleInfoList)) {
            for (RoleInfo roleInfo : roleInfoList) {
                if ("R_Developer".equals(roleInfo.getRolename())) {
                    return true;
                }
            }
        }
        return false;
    }

    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    @ResponseBody
    @OperateLog(value = "系统级别添加用户", descriptionGenerator = ManagerSaveGenerator.class)
    public SimpleResponseBody save(HttpServletRequest request, Model model, String repasswd, MUserSaveInfo muserSaveInfo, String ridListStr, String unitList) {

        logger.debug("password->" + passwordEncoder.encode(muserSaveInfo.getPasswd()));
        logger.debug("muserSaveInfo->" + muserSaveInfo);

        SimpleResponseBody<MUserInfo> srb = new SimpleResponseBody<MUserInfo>();
        ;
        srb.setOk(false);
        if (!repasswd.equals(muserSaveInfo.getPasswd())) {
            srb.setMsg("两次输入的密码不一致");
        } else {
            muserSaveInfo.setPasswd(passwordEncoder.encode(muserSaveInfo.getPasswd()));
            String[] ridStrs = ridListStr.split("#");
            List<Long> ridLList = new ArrayList<>();
            for (String ridStr : ridStrs) {
                try {
                    long rid = Long.parseLong(ridStr);
                    ridLList.add(rid);
                } catch (NumberFormatException ex) {
                }
            }
            muserSaveInfo.setRidList(ridLList);
            try {
                muserservice.addUser(muserSaveInfo);
                srb.setOk(true);
                srb.setMsg("用户添加成功");
            } catch (Exception ex) {
                logger.warn(ex.getMessage(), ex);
                srb.setMsg("发生了未知错误");
            }
        }

        return srb;
    }

    /*
    * 跳转至搜索界面，将选项条件一并发送过去。
    * */
    @RequestMapping("/list")
    public String toList(Model model) {
        model.addAttribute("title","用户管理");
        try {
            List roleInfoList = muserservice.getRoles();
            if (!isDeveloper()) {
                Iterator<RoleInfo> iterator = roleInfoList.iterator();
                while (iterator.hasNext()) {
                    RoleInfo roleInfo = iterator.next();
                    if ("R_Developer".equals(roleInfo.getRolename())) {
                        iterator.remove();
                    }
                }
            }
            model.addAttribute("rolelist", roleInfoList);
            model.addAttribute("userStatusList", UserStatus.getAll());

            //查出所有的菜单
            ManageMenuDboSearchCondition manageMenuDboSearchCondition=new ManageMenuDboSearchCondition();
            manageMenuDboSearchCondition.setMax(Integer.MAX_VALUE);
            ManageMenuDboCollection manageMenuDboCollection = manageMenuService.searchByCondition(manageMenuDboSearchCondition);
            logger.debug("manageMenuDboCollection->"+manageMenuDboCollection);
            List<ManageMenuVo> manageMenuVoList=new ArrayList<>();
            if(manageMenuDboCollection.getTotalCount()>0){
                for (ManageMenuDbo manageMenuDbo:manageMenuDboCollection.getEntityList()){
                    if(manageMenuDbo.getMenuUrl()!=null&&manageMenuDbo.getMenuUrl().startsWith("/")){
                        ManageMenuVo manageMenuVo= PojoConvertUtil.convertPojo(manageMenuDbo,ManageMenuVo.class);
                        manageMenuVoList.add(manageMenuVo);
                    }
                }
            }
            model.addAttribute("manageMenuVoList",manageMenuVoList);

        } catch (Exception e) {
            logger.error("未知异常");
        }
        return "system/manager/user_list";
    }

    /**
     * 查询用户各项信息
     */
    @RequestMapping("/listSearch")
    @ResponseBody
    public SimpleListResult List(String username,
                                 String realname,
                                 Long rid,
                                 @RequestParam(value = "page", defaultValue = "1")int page,
                                 @RequestParam(value = "max", defaultValue = "10")int max) {
        MUserDetailSearchCondition mds = new MUserDetailSearchCondition();
        SimpleListResult slr = new SimpleListResult();

        mds.setUsername(username);
        mds.setRealName(realname);
        mds.setRid(rid);

        int offset = (page - 1) * max;
        logger.debug("offset->" + offset + ",max->" + max);
        SearchParams searchParams = new SearchParams();
        searchParams.setOffset(offset);
        searchParams.setMax(max);
        mds.setSearchParams(searchParams);

        try {
            MUserDetailCollection mdc = muserservice.searchByCondition(mds);
            List<MUserDetail> mdList = mdc.getMuserDetailList();
            List<SimpleMUserDetailResult> smdList = new ArrayList<SimpleMUserDetailResult>();
            SimpleMUserDetailResult smd = null;
            for (int i = 0; i < mdList.size(); i++) {
                mdList.get(i).setPasswd("");
                if (!isDeveloper()) {
                    List<RoleInfo> roleInfoList = mdList.get(i).getRoleInfoList();
                    if (isDeveloper(roleInfoList)) {
                        continue;
                    }
                }
                smd = new SimpleMUserDetailResult();
                DataConverter<MUserDetail, SimpleMUserDetailResult> dataConverter = new DataConverter<MUserDetail, SimpleMUserDetailResult>(mdList.get(i), smd);
                dataConverter.convert();
                smdList.add(smd);

            }
            slr.setRows(smdList);
            slr.setCurrentPage(page);
            slr.setResults(mdc.getTotalCount());
            slr.setPages(PageService.countPages(max, slr.getResults()));
        } catch (Exception e) {
            logger.error("未知错误", e);
        }
        return slr;
    }

    /*
    * 删除用户
    * */
    @RequestMapping(value = "/delUser",method = RequestMethod.POST)
    @ResponseBody
    @OperateLog(value = "系统级别删除用户", descriptionGenerator = ManagerDelUserGenerator.class)
    public String delUser(Long userId) {
        String msg = "ok";
        try {
            muserservice.delUser(userId);
        } catch (Exception e) {
            msg = "发生了未知的错误";
            logger.error("发生了未知的错误",e);
        }

        return msg;
    }

    /**
     * 保存修改的内容
     */
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    @OperateLog(value = "系统级别编辑用户", descriptionGenerator = ManagerSaveUserGenerator.class)
    @ResponseBody
    public SimpleResponseBody saveUser(HttpServletRequest request, Model model, String repasswd, MUserSaveInfo muserSaveInfo, String ridListStr, String unitList) {

        logger.debug("password->" + passwordEncoder.encode(muserSaveInfo.getPasswd()));
        logger.debug("muserSaveInfo->" + muserSaveInfo);

        SimpleResponseBody<MUserInfo> srb = new SimpleResponseBody<MUserInfo>();
        ;
        srb.setOk(false);
        if (!repasswd.equals(muserSaveInfo.getPasswd())) {
            srb.setMsg("两次输入的密码不一致");
        } else {
            if (!StringUtils.isEmpty(muserSaveInfo.getPasswd())) {
                //对密码进行加密
                muserSaveInfo.setPasswd(passwordEncoder.encode(muserSaveInfo.getPasswd()));
            }
            if(ridListStr!=null) {
                String[] ridStrs = ridListStr.split("#");
                List<Long> ridLList = new ArrayList<>();
                for (String ridStr : ridStrs) {
                    try {
                        long rid = Long.parseLong(ridStr);
                        ridLList.add(rid);
                    } catch (NumberFormatException ex) {
                    }
                }
                muserSaveInfo.setRidList(ridLList);
            }

            try {
                muserservice.modifyUser(muserSaveInfo);
                srb.setOk(true);
                srb.setMsg("用户修改成功");
            } catch (Exception ex) {
                srb.setMsg("发生了未知错误");
                logger.warn(ex.getMessage(), ex);
            }
        }

        return srb;

    }

}
